<?php
/**
 * @desc 微信.异步通知
 * @document https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxNotify extends WxConfig
{
    public function run($callback)
    {
        return $this->handle($callback);
    }

    /**
     * @param $callback
     * @return string
     * callback为商家业务逻辑处理回调函数，处理成功后返回true（已验证签名）
     */
    public function handle($callback)
    {
        $xml = @file_get_contents('php://input');
        $post = Common::xmlToArray($xml);
        $verifySign = $this->verifySign($post);
        if ($verifySign === true && $post['result_code'] == 'SUCCESS' && $post['return_code'] == 'SUCCESS') {
            $data = [
                'order_sn' => $post['out_trade_no'],
                'trade_no' => $post['transaction_id'],
                'total_amount' => $post['total_fee']/100//交易总金额
            ];
            if ($callback($data) === true) {
                return $this->returnResult('SUCCESS', 'OK');
            } else {
                return $this->returnResult('FAIL', '未知错误');
            }
        } else {
            return $this->returnResult('FAIL', '签名失败');
        }
    }
}